package com.example.dee.threadRun;

import com.example.dee.config.ParamConfig;
import com.example.dee.pojo.CarData;
import com.example.dee.pojo.vo.CarDataUp;
import com.example.dee.pojo.vo.ResponseJSON;
import com.example.dee.service.SysService;
import com.example.dee.util.RandomUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static com.example.dee.controller.CarDataUpController.doPost;

/**
 * @ClassName UpDataRunnable
 * @创建人 李劲松
 * @创建时间 2022/7/25 8:59
 * @描述
 */
public class UpDataRunnable implements Runnable{
    private String id;
    @Resource
    private SysService sysService;
    private int sysId;

    public SysService getSysService() {
        return sysService;
    }

    public void setSysService(SysService sysService) {
        this.sysService = sysService;
    }

    public int getSysId() {
        return sysId;
    }

    public void setSysId(int sysId) {
        this.sysId = sysId;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public UpDataRunnable(String id,int sysId,SysService sysService) {
        this.sysService=sysService;
        this.id = id;
        this.sysId=sysId;
    }
    @Override
    public void run() {
        CarData carData = sysService.selectCarData(id);
        String url= ParamConfig.URL_B;
        String res = null;
        if (carData!=null) {
            Map<String, Object> paramMap = new HashMap<>();
            ObjectMapper mapper = new ObjectMapper();
            String jsonStr = null;
            try {
                jsonStr = mapper.writeValueAsString(new CarDataUp(carData));
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
            paramMap.put("param", jsonStr);
            paramMap.put("command", sysService.selectCommand());
            try {
                res = doPost(url, paramMap);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
            ResponseJSON resJson = null;
            try {
                resJson = mapper.readValue(res, ResponseJSON.class);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
            if (ParamConfig.STATE_TRUE.equals(resJson.getSubCode())) {
                System.out.println(id);
                System.out.println(resJson.getInfo());
            } else {
            }
            //修改车辆信息上传状态与操作描述
            sysService.updateCarDataState(id, resJson, RandomUtil.getDateFormat(new Date()));
            sysService.addRecord(carData, resJson.getInfo(), sysId);
            System.out.println(resJson);
        }
    }
}
